// 加密解密
import forge from 'node-forge'
// 密钥
const keyStr = 'zoNE32byteexamplekeyforaes256gcm'
/**
 *
 * @param word 需要的加密值
 * @return {string}
 */
export function encrypt(word) {
  const iv = forge.random.getBytesSync(12) // 生成随机iv 12字节
  const cipher = forge.cipher.createCipher('AES-GCM', keyStr) // 生成AES-GCM模式的cipher对象 并传入密钥
  cipher.start({
    iv,
  })
  cipher.update(forge.util.createBuffer(forge.util.encodeUtf8(word)))
  cipher.finish()
  const encrypted = cipher.output
  const tag = cipher.mode.tag
  return window.btoa(iv + encrypted.data + tag.data)
}

/**
 *
 * @param datamsg 需要的解密值
 * @return {string}
 */
export function decrypt(datamsg) {
  datamsg = window.atob(datamsg)
  // datamsg = decodeURIComponent(escape(atob(datamsg)));
  const iv = datamsg.slice(0, 12)//获取生成的随机iv12字节
  const tag = datamsg.slice(-16)//获取最后的16位认证标记
  const data = datamsg.slice(12, datamsg.length - 16)//将12字节后和倒数16字节之间的字节作为密文
  const decipher = forge.cipher.createDecipher('AES-GCM', keyStr)
  decipher.start({
    iv,
    tag,
  })
  decipher.update(forge.util.createBuffer(data))
  const pass = decipher.finish()
  if (pass) {
    return decipher.output.toString()
  }
}